package com.chen.handler;

import com.chen.constant.ResultConstant;
import com.chen.exception.*;
import com.chen.results.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@RestControllerAdvice
@Slf4j
public class GlobalException {


    @ExceptionHandler({PasswordError.class, EmailNotExist.class, NotFoundUserError.class})
    public Result NotFoundHandler(BaseException e) {
        e.printStackTrace();
        return Result.error(ResultConstant.CODE_NOT_FOUND, e.getMessage());
    }

    @ExceptionHandler(NotLoginError.class)
    public Result notLoginErrorHandler(NotLoginError e) {
        e.printStackTrace();
        return Result.error(ResultConstant.CODE_UNAUTHORIZED_ERROR, e.getMessage());
    }

    @ExceptionHandler(NoPermissionError.class)
    public Result notLoginErrorHandler(NoPermissionError e) {
        e.printStackTrace();
        return Result.error(ResultConstant.CODE_NO_PERMISSION, e.getMessage());
    }


    // 参数错误
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        return Result.error(ResultConstant.CODE_OTHER_ERROR, ResultConstant.MSG_DATA_ERROR);
    }

    @ExceptionHandler({RuntimeException.class, SQLException.class})
    public Result exceptionHandler(Exception e) {
        e.printStackTrace();
        if (e.getMessage().contains("SQL")) {
            log.error("SQL 语句异常");
            if (e.getMessage().contains("users.email")) {
                return Result.error(ResultConstant.CODE_OTHER_ERROR, ResultConstant.MSG_EMAIL_EXIST);
            }
            if (e.getMessage().contains("contact_group.group_name")) {
                return Result.error(ResultConstant.CODE_OTHER_ERROR, ResultConstant.MSG_GROUP_NAME_EXIST);
            }

        }

        return Result.error(ResultConstant.CODE_OTHER_ERROR, ResultConstant.MSG_UNKNOWN_ERROR);
    }

}
